package servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.UserActions;

/**
 * Servlet implementation class logIn_servlet
 */
@WebServlet("/login")
public class LogIn_servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	UserActions userActionsBean;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogIn_servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doLogin(request, response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doLogin(request, response);
	}



	private void doLogin(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			
			
			boolean res = userActionsBean.loginAction(request.getParameter("userId"), request.getParameter("password"));
			
			if(res){
				 try {
					 request.getSession().setAttribute("logged_user", request.getParameter("userId"));
					 getServletContext().getRequestDispatcher("/user_home.jsp").forward(request, response);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
			else{
				response.getWriter().println("<html>");
				response.getWriter().println("<body>");
				response.getWriter().println("USER_ID: " + request.getParameter("userId") + " - PASSWORD: " + request.getParameter("password"));
				response.getWriter().println("<BR>");
				response.getWriter().println(res ? "SUCCESS" : "FAIL");
				response.getWriter().println("</body>");
				response.getWriter().println("</html>");
			}
			
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
